package upgrade

import (
	"context"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/sagoo-cloud/sagooiot/internal/consts"
	"github.com/sagoo-cloud/sagooiot/internal/dao"
	"github.com/sagoo-cloud/sagooiot/internal/model"
	"github.com/sagoo-cloud/sagooiot/internal/service"
)

type sUpgradeDevOtaModule struct{}

func sUpgradeDevOtaModuleNew() *sUpgradeDevOtaModule {
	return &sUpgradeDevOtaModule{}
}
func init() {
	service.RegisterUpgradeDevOtaModule(sUpgradeDevOtaModuleNew())
}

// GetDevOtaModuleList 获取列表数据
func (s *sUpgradeDevOtaModule) GetDevOtaModuleList(ctx context.Context, in *model.GetDevOtaModuleListInput) (total, page int, list []*model.DevOtaModuleOutput, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.DevOtaModule.Ctx(ctx).InnerJoin("dev_product ", "dev_product.id = dev_ota_module.product_id")
		if in.ProductId != 0 {
			m = m.Where(dao.DevOtaModule.Columns().ProductId, in.ProductId)
		}
		total, err = m.Count()
		if err != nil {
			err = gerror.New("获取总行数失败")
			return
		}
		page = in.PageNum
		if in.PageSize == 0 {
			in.PageSize = consts.PageSize
		}
		err = m.Fields("dev_ota_module.*,dev_product.name product_name").Page(page, in.PageSize).Order("created_at desc").Scan(&list)
		if err != nil {
			err = gerror.New("获取数据失败")
		}
	})
	return
}

// GetDevOtaModuleById 获取指定ID数据
func (s *sUpgradeDevOtaModule) GetDevOtaModuleById(ctx context.Context, id int) (out *model.DevOtaModuleOutput, err error) {
	err = dao.DevOtaModule.Ctx(ctx).Where(dao.DevOtaModule.Columns().Id, id).Scan(&out)
	return
}

// AddDevOtaModule 添加数据
func (s *sUpgradeDevOtaModule) AddDevOtaModule(ctx context.Context, in model.DevOtaModuleAddInput) (err error) {
	_, err = dao.DevOtaModule.Ctx(ctx).Insert(in)
	return
}

// EditDevOtaModule 修改数据
func (s *sUpgradeDevOtaModule) EditDevOtaModule(ctx context.Context, in model.DevOtaModuleEditInput) (err error) {
	dao.DevOtaModule.Ctx(ctx).FieldsEx(dao.DevOtaModule.Columns().Id).Where(dao.DevOtaModule.Columns().Id, in.Id).Update(in)
	return
}

// DeleteDevOtaModule 删除数据
func (s *sUpgradeDevOtaModule) DeleteDevOtaModule(ctx context.Context, Ids []int) (err error) {
	_, err = dao.DevOtaModule.Ctx(ctx).Delete(dao.DevOtaModule.Columns().Id+" in (?)", Ids)
	return
}
